﻿using System.Data.Entity;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using SuppKids.Core.Data;
using SuppKids.Core.Providers;
using SuppKids.Core.Repository;

namespace SuppKids.IoC.Installers
{
	public class RepositoriesInstaller : IWindsorInstaller
	{
		public void Install(IWindsorContainer container, IConfigurationStore store)
		{
			string databasePath = container.Resolve<IApplicationSettingsProvider>().DatabasePath;

			container.Register(Component.For<IDataContext, DbContext>()
				.ImplementedBy<ApplicationDBContext>().DependsOn(Dependency.OnValue<string>(databasePath))
				.LifestylePerThread());
			container.Register(this.FindRepositories()
				.Configure(x => x.LifeStyle.Transient.Configuration()));
		}

		private BasedOnDescriptor FindRepositories()
		{
			var res = Types.FromAssemblyContaining(typeof(IRepository<>))
				.BasedOn(typeof(IRepository<>))
				.If(t => t.Name.EndsWith("Repository"))
				.WithService
				.Self();

			return res;
		}
	}
}